package global

import (
	"sync"
)

type Service struct {
	Encode int    `json:"encode"`
	Port   int    `json:"port"`
	Token  string `json:"token"`
	Type   string `json:"type"`
	Host   string `json:"host,omitempty"` // omitempty表示该字段在JSON中可能不存在
}

type Frame struct {
	Enabled       bool  `json:"enable"`
	LogicInterval uint8 `json:"logic_interval"`
	Rate          uint8 `json:"rate"`
}

//go:inline
func (f *Frame) GetFrameInterval() int {
	return 1000 / int(f.Rate)
}

type Config struct {
	NodeID      string              `json:"node_id"`
	Host        string              `json:"host"`
	HTTP        *Service            `json:"http"`
	LogDir      string              `json:"log_dir"`
	LogLevel    string              `json:"log_level"`
	MongoURI    string              `json:"mongo_uri"`
	RedisURI    string              `json:"redis_uri"`
	RemotePorts map[string]*Service `json:"remote_ports"` // map[string]Service表示key为NodeID，value为Service
	RPC         *Service            `json:"rpc"`
	Type        string              `json:"type"`
	WebSocket   *Service            `json:"websocket"`
	Frame       Frame               `json:"frame"`

	sync.Mutex

	// 生成列相关属性
	RemoteRpcNodeIDs []string // 用于存储所有的rpc节点id
}

func (config *Config) GetRemoteNodeAddr(nodeID string) *Service {
	config.Lock()
	defer config.Unlock()
	service, exists := config.RemotePorts[nodeID]
	if !exists {
		return nil
	}
	return service
}

func (config *Config) InitGeneratedFields() {
	config.Lock()
	defer config.Unlock()
	config.RemoteRpcNodeIDs = make([]string, 0)
	for nodeID := range config.RemotePorts {
		config.RemoteRpcNodeIDs = append(config.RemoteRpcNodeIDs, nodeID)
	}
}
